<%@page import="com.shuohe.entity.system.user.User"%>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ page language="java" import="java.util.*"%>
<%@ page import="com.shuohe.util.json.*" %>
<%@page import="java.io.PrintWriter"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
    String formName = request.getParameter("formName");
    User user = null;
    String userJson = null;
    String permissionssJson = null;
    PrintWriter ss = response.getWriter();
    try
    {
        user = (User)session.getAttribute("user");
        if(user==null)
        {
          System.out.println("user = null");
          //response.sendRedirect(basePath+"/pages/login.jsp");
          String topLocation = "<script>top.location.href=\""+basePath+"/pages/login.jsp\"</script>";
          ss.print(topLocation);
        }
        else
        {
            userJson = Json.toJsonByPretty(user);
        }
    }
    catch(Exception e)
    {
        String topLocation = "<script>top.location.href=\""+basePath+"/pages/login.jsp\"</script>";
        ss.print(topLocation);
        e.printStackTrace();
    }
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
<meta name="renderer" content="webkit">
<title>图表</title>
<link type="text/css" href="<%=basePath%>/TopJUI/topjui/css/topjui.core.min.css" rel="stylesheet">
<link type="text/css" href="<%=basePath%>/TopJUI/topjui/themes/default/topjui.green.css" rel="stylesheet" id="dynamicTheme" />
<link type="text/css" href="<%=basePath%>/TopJUI/topjui/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" />
<link type="text/css" href="<%=basePath%>/pages/css/add-form.css" rel="stylesheet" />
</head>
<body>
<div class="easyui-layout">
  <div class="charts-form-set">
    <label>请选择：</label>
    <input class="easyui-combobox" id="charts" data-options="width:400,editable:false" />
  </div>
  <div id="searchCon" style="padding:10px;">

  </div>
  <div id="chartDiv" style="width:100%;height:450px;"></div>
</div>
</body>
</html>
<script type="text/javascript" src="<%=basePath%>/TopJUI/topjui/plugins/jquery/jquery.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/TopJUI/topjui/plugins/jquery/jquery.cookie.js"></script>
<script type="text/javascript" src="<%=basePath%>/TopJUI/static/public/js/topjui.config.js"></script>
<script type="text/javascript" src="<%=basePath%>/TopJUI/topjui/js/topjui.core.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/TopJUI/topjui/js/locale/topjui.lang.zh_CN.js"></script>
<script type="text/javascript" src="<%=basePath%>/pages/js/moment.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/pages/js/layer/layer.js"></script>
<script type="text/javascript" src="<%=basePath%>/pages/js/util.js"></script>
<script type="text/javascript" src="<%=basePath%>/pages/js/base-loading.js"></script>
<script type="text/javascript" src="<%=basePath%>/pages/js/echarts.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/pages/js/add-form.js"></script>
<script type="text/javascript">
var basePath = '<%=basePath%>'
var formName = '<%=formName%>'
var user = <%=userJson%>
var chartsRows = []
var option
var fields = parent.fields
var chartObj
var myChart = echarts.init(document.getElementById('chartDiv'))
$(function(){
  init()
})
function init () {
  $.ajax({
    url: "<%=basePath%>/crm/ActionFormSelectUtil/Select/getChartsByFormName.do",
    type: "POST",
    dataType:'json',
    data:
    {
      'formName': formName
    },
    error: function() //失败
    {
      messageloadError()
    },
    success: function(result)//成功
    {
      chartsRows = result.rows
      $('#charts').combobox({
        data: chartsRows,
        valueField:'id',
        textField:'name',
        onSelect: function (rec) {
          initChart(rec)
        }
      })
    }
  })
}
function initChart (result) { //选择图表后生成条件
  chartObj = result
  var searchs = JSON.parse(result.searchs)
  chartObj.searchs = searchs
  console.log(searchs)
  var temp = ''
  var tempJs = ''
  for (var i = 0; i < searchs.length; i++) {
    for (var j = 0; j < fields.length; j++) {
      if (fields[j].text == searchs[i].field) {
        if (fields[j].fieldType == 'textboxMultiline') {
          fields[j].fieldType = 'textbox'
        }
        if (i != 0) {
          temp += formatterManner(searchs[i].manner,null,null)
        }
        temp += fields[j].title + formatterCondition(searchs[i].condition,null,null) + '<input type="text" id="search'+i+'" class="easyui-'+fields[j].fieldType+'" />'
        if (fields[j].fieldType == 'combobox') {
          if (fields[j].selectType == '0') {
            tempJs += 'var ' + fields[j].text + 'ComboboxData=[]; \n '
            tempJs += '$.ajax({ \n url: basePath+"/crm/ActionFormUtil/getByTableName.do?tableName='+fields[j].selectID+'", \n type: "POST", \n '
            tempJs += 'dataType:"json", \n data:{}, \n async:false, \n error:function(){ \n messageloadError(); \n '
            tempJs += '}, \n success:function(data){ \n ' + fields[j].text + 'ComboboxData=data.rows; \n '
            tempJs += ' \n } \n }); \n '
            tempJs += '$("#search'+i+'").combobox({data:'+field.text+'ComboboxData,valueField:\'id\',textField:\'text\'});'
          } else if (fields[j].selectType == '1') {
            tempJs += '$("#search'+i+'").combobox({url:basePath+\'/develop/url/getUrl.do?name='+fields[j].selectID+'\',valueField:\'id\',textField:\'text\'});'
          }
        } else {
          tempJs += '$("#search'+i+'").'+fields[j].fieldType+'({});'
        }
      }
    }
  }
  temp += '<select class="easyui-combobox" id="count"><option value="20">最近20条</option><option value="30">最近30条</option><option value="40">最近40条</option><option value="50">最近50条</option><option value="80">最近80条</option><option value="100">最近100条</option></select>'
  temp += '<button type="button" class="button-default" onclick="creatChart()">生成图表</button>'
  tempJs += '$("#count").combobox({});'
  console.log(tempJs)
  $('#searchCon').html(temp)
  var script = document.createElement("script")
  script.type = "text/javascript"
  try {
    script.appendChild(document.createTextNode(tempJs))
  } catch (ex) {
    script.text = tempJs
  }
  document.body.appendChild(script)
}
function creatChart () { // 拼装条件取数据
  var searchs = chartObj.searchs
  var condition = ''
  for (var i = 0; i < searchs.length; i++) {
    if ($.trim($('#search'+i).textbox('getValue')) != '') {
      condition += ' '+searchs[i].manner+' '+searchs[i].field+' '+searchs[i].condition+' '
      if (searchs[i].condition == 'like' || searchs[i].condition == 'not like') {
        condition += ' \'%'+$.trim($('#search'+i).textbox('getValue'))+'%\' '
      } else {
        condition += ' \''+$.trim($('#search'+i).textbox('getValue'))+'\' '
      }
    }
  }
  if ($('#count').combobox('getValue')!='') {
    condition += ' limit 0,'+$('#count').combobox('getValue')
  }
  console.log(condition)
  $.ajax({
    url: "<%=basePath%>/crm/ActionFormSelectUtil/Select/getChartsDataBySearch.do",
    type: "POST",
    dataType:'text',
    async: false,
    data:
    {
      'formName': formName,
      'field': chartObj.x_field,
      'condition': condition,
      'create_user_id': user.id
    },
    error: function() //失败
    {
      messageloadError()
    },
    success: function(data)//成功
    {
      //console.log(data)
      chartObj.xData = data.split(',')
    }
  })
  $.ajax({
    url: "<%=basePath%>/crm/ActionFormSelectUtil/Select/getChartsDataBySearch.do",
    type: "POST",
    dataType:'text',
    async: false,
    data:
    {
      'formName': formName,
      'field': chartObj.y_field,
      'condition': condition,
      'create_user_id': user.id
    },
    error: function() //失败
    {
      messageloadError()
    },
    success: function(data)//成功
    {
      //console.log(data)
      chartObj.yData = data.split(',')
    }
  })
  setCharts(chartObj)
}
function setCharts (result) { // 生成图表
  console.log(result)
  if (result.type == 'line' || result.type == 'bar')  {
    option = {
      title: {
        text: result.name,
        left: 'center'
      },
      tooltip: {
        trigger: 'axis'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      toolbox: {
        feature: {
          magicType: {
            type: ['line', 'bar']
          },
          restore: {show: true},
          saveAsImage: {show: true}
        },
        right: 25
      },
      xAxis: {
        type: 'category',
        boundaryGap: true,
        name: result.name_x,
        nameLocation: 'center',
        nameGap: 20,
        data: result.xData
      },
      yAxis: {
        type: 'value',
        name: result.name_y
      },
      series: [
        {
          name:result.name_y,
          type:result.type,
          data:result.yData
        }
      ]
    }
  } else if (result.type == 'pie') {
    var pieData = []
    for (var i = 0; i < result.xData.length; i++) {
      pieData.push({
        name: result.xData[i],
        value: result.yData[i]
      })
    }
    option = {
      title : {
        text: result.name,
        x:'center'
      },
      tooltip : {
        trigger: 'item',
        formatter: "{a} <br/>{b} : {c} ({d}%)"
      },
      toolbox: {
        feature: {
          restore: {show: true},
          saveAsImage: {show: true}
        },
        right: 25
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: result.xData
      },
      series : [
        {
          name: result.name_y,
          type: 'pie',
          radius : '75%',
          center: ['50%', '60%'],
          data:pieData,
          itemStyle: {
            emphasis: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
  }
  myChart.clear()
  myChart.setOption(option)
}
</script>
